package cn.wolfcode.edu.realm;

import cn.wolfcode.edu.domain.Employee;
import cn.wolfcode.edu.mapper.EmployeeMapper;
import cn.wolfcode.edu.mapper.PermissionMapper;
import cn.wolfcode.edu.mapper.RoleMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by abb on 2018-07-07.
 */
public class UserRealm extends AuthorizingRealm{

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    public String getName(){
        return "UserRealm";
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Employee employee = (Employee)principals.getPrimaryPrincipal();
        List<String> roleSns = new ArrayList<String>();
        List<String> permissionResources = new ArrayList<String>();
        if(employee.isAdmin()){
            roleSns = roleMapper.getAllSns();
            permissionResources = Arrays.asList("*:*");
        }else{
            roleSns = roleMapper.getSnsByEmployeeId(employee.getId());
            permissionResources = permissionMapper.getPermsByEmployeeId(employee.getId());
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roleSns);
        info.addStringPermissions(permissionResources);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String)token.getPrincipal();
        Employee employee = employeeMapper.getByUserName(username);
        if(employee == null){
            return null;
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(employee, employee.getPassword(),
                ByteSource.Util.bytes(employee.getUsername()), getName());
        /*SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(employee, employee.getUsername(),
               getName());*/

        return info;
    }
}
